package com.ruoyi.websocket.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.websocket.domain.WebSocketMessage;
import com.ruoyi.websocket.handler.MessageWebSocketHandler;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket相关API
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/websocket/api")
public class WebSocketController extends BaseController {

    /**
     * 获取在线用户数量
     */
    @GetMapping("/online/count")
    public AjaxResult getOnlineCount() {
        int count = MessageWebSocketHandler.getOnlineUserCount();
        return success(count);
    }

    /**
     * 检查用户是否在线
     */
    @GetMapping("/online/status/{userId}")
    public AjaxResult checkUserOnline(@PathVariable("userId") Long userId) {
        boolean isOnline = MessageWebSocketHandler.isUserOnline(userId);
        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("isOnline", isOnline);
        return success(result);
    }

    /**
     * 发送消息给指定用户（管理员功能）
     */
    @PostMapping("/send/user/{userId}")
    public AjaxResult sendMessageToUser(@PathVariable("userId") Long userId, @RequestBody Map<String, String> params) {
        try {
            String content = params.get("content");
            String type = params.getOrDefault("type", "message");
            
            WebSocketMessage message = new WebSocketMessage(type, content);
            MessageWebSocketHandler.sendMessageToUser(userId, message);
            
            return success("消息发送成功");
        } catch (Exception e) {
            return error("消息发送失败：" + e.getMessage());
        }
    }

    /**
     * 广播消息给所有用户（管理员功能）
     */
    @PostMapping("/send/broadcast")
    public AjaxResult broadcastMessage(@RequestBody Map<String, String> params) {
        try {
            String content = params.get("content");
            String type = params.getOrDefault("type", "message");
            
            WebSocketMessage message = new WebSocketMessage(type, content);
            MessageWebSocketHandler.broadcastMessage(message);
            
            return success("广播消息发送成功");
        } catch (Exception e) {
            return error("广播消息发送失败：" + e.getMessage());
        }
    }
}
